/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.product.web.BrandAction
   Module Description   :

   Date Created      : 2009/12/14
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.product.web;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.product.entity.Brand;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author ellen.li
 * 
 */
public class BrandAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = -3599788867186224211L;
	private final Logger logger = LoggerFactory.getLogger(BrandAction.class);
	private ProductService productService;
	@Resource(name = "menuService")
	private DomainService<Menu> menuService;
	private SimplePager pager;
	CommonCriteria crit;
	private List<Brand> brands;
	private String[] brandDelete;
	private Brand brand;
	private String brandId;
	private String brandNameParam;
	private String briefNameParam;
	private String brandStatusParam;
	private String brandStoryParam;
	private String brandEnameParam;
	private String brandSynonymParam;
	private File[] upload;
	private String[] uploadFileName;// 设置上传文件的文件名
	@Resource
	private BaseManager baseMgr;

	private Menu statusTypeMenu;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (pager == null) {
			pager = new SimplePager();
		}
		if (null == statusTypeMenu) {
			statusTypeMenu = menuService.get("Member.BlockStatus");
		}
		logger.info("prepare ok");
	}

	/* 品牌列表 */
	public String list() throws Exception {
		String[] sortOrder = { "modifyDate desc" };
		crit = new CommonCriteria();
		int entitySize = 0;
		brands = null;
		// 沒有輸入品牌名稱
		if (StringUtils.isBlank(brandNameParam)) {
			if (StringUtils.isNotBlank(brandStatusParam)) {
				crit.addEq("brandStatus", brandStatusParam);
			}
			entitySize = productService.getBrandListSize(crit).intValue();
			pager.setTotalSize(entitySize);
			pager.setPageRecord(10);
			if (entitySize <= pager.getPageRecord() * pager.getCurrentPage()) {
				pager.setCurrentPage((entitySize / pager.getPageRecord()) + (entitySize % pager.getPageRecord() > 0 ? 1 : 0));
			}
			if (entitySize == 0 && !brandStatusParam.equals("N")) {
				addActionMessage("找不到品牌资料，请<a href='add.do'>新增品牌</a>资料");
			} else {
				brands = productService.getBrandList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(),
						crit, sortOrder);
			}
			return "list";
		}
		// 先搜尋中文名稱
		crit.addRlike("brandName", brandNameParam);
		if (StringUtils.isNotBlank(brandStatusParam)) {
			crit.addEq("brandStatus", brandStatusParam);
		}
		entitySize = productService.getBrandListSize(crit).intValue();
		// 有找到就不再搜尋英文名稱
		if (entitySize != 0) {
			pager.setTotalSize(entitySize);
			pager.setPageRecord(10);
			if (entitySize <= pager.getPageRecord() * pager.getCurrentPage()) {
				pager.setCurrentPage((entitySize / pager.getPageRecord()) + (entitySize % pager.getPageRecord() > 0 ? 1 : 0));
			}
			brands = productService.getBrandList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(), crit,
					sortOrder);
			return "list";
		}
		// 搜尋不分大小寫的英文名稱
		entitySize = productService.getBrandList(0, -1, brandNameParam, brandStatusParam).size();
		pager.setTotalSize(entitySize);
		pager.setPageRecord(10);// defaut 20
		if (entitySize == 0 && !brandStatusParam.equals("N")) {
			addActionMessage("找不到" + brandNameParam + "品牌资料，请<a href='add.do'>新增品牌</a>资料");
		} else {
			if (entitySize <= pager.getPageRecord() * pager.getCurrentPage()) {
				pager.setCurrentPage((entitySize / pager.getPageRecord()) + (entitySize % pager.getPageRecord() > 0 ? 1 : 0));
			}
			brands = productService.getBrandList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(),
					brandNameParam, brandStatusParam);
		}
		return "list";
	}

	public String delBrand() throws Exception {
		if (brandDelete != null) { // delete brand
			for (int i = 0; i < brandDelete.length; i++) {
				brand = productService.getBrandByBrandId(brandDelete[i]);
				productService.delBrand(brand);
			}
		}
		return list();
	}

	/* 編輯品牌 */
	public String edit() throws Exception {
		if (brandId != null || brand.getBrandId() != null) {
			try {
				if (StringUtils.isNotBlank(brandId)) {
					brand = productService.getBrandByBrandId(brandId);
					setBrandStoryParam(productService.readBrandFromFile(brandId));
				} else {
					brand = productService.getBrandByBrandId(brand.getBrandId());
				}
			} catch (CoreException e) {
				addActionError(e.getMessage());
				e.printStackTrace();
			}
		}
		return "edit";
	}

	/**
	 * 儲存品牌 *
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		String returnValue = "false";
		StringBuffer brandSql = new StringBuffer();
		Object[] brandAy;
		brandSql.append("from Brand where brandName like ? or brandEname like ? or brandSynonym like ? ");
		brandAy = baseMgr.queryByHql(brandSql.toString(),
				new Object[] { brandNameParam, brandEnameParam, brandSynonymParam });
		if (brandAy.length > 0) {
			if ((!StringUtils.isBlank(brandId))) {
				returnValue = saveBrand();
			} else {
				addActionMessage("品牌名稱或同義詞已存在於資料庫中");
				brand = new Brand();
				brand.setBrandName(brandNameParam);
				brand.setBriefName(briefNameParam);
				setBrandStoryParam(brandStoryParam);
				brand.setBrandStatus(brandStatusParam);
				brand.setBrandEname(brandEnameParam);
				brand.setBrandSynonym(brandSynonymParam);
				returnValue = "false";
				return "edit";
			}
		} else {
			returnValue = saveBrand();
		}
		if ("true".equals(returnValue)) {
			return list();
		} else {
			return "edit";
		}
	}

	public String saveBrand() throws Exception {
		String returnValue = "false";
		try {
			if (StringUtils.isBlank(brandId)) {
				brand = new Brand();
			} else {
				brand = productService.getBrandByBrandId(brandId);
			}
			brand.setBrandName(brandNameParam);
			brand.setBriefName(briefNameParam);
			// brand.setBrandStory(brandStoryParam);
			brand.setBrandStatus(brandStatusParam);
			brand.setBrandEname(brandEnameParam);
			brand.setBrandSynonym(brandSynonymParam);
			Brand saveBrand = productService.saveBrand(brand);
			if (null != upload) {
				String filename = ServerValue.getFrontApachePath() + File.separator + "static" + File.separator + "brand"
						+ File.separator;
				FileUtils.forceMkdir(new File(filename + File.separator + brand.getBrandId() + File.separator));
				StringBuffer sbMainPath = new StringBuffer();
				sbMainPath.setLength(0);
				sbMainPath.append(filename).append(File.separator).append(brand.getBrandId()).append(File.separator).append(
						brand.getBrandId()).append(".jpg");
				for (int i = 0; i < upload.length; i++) {
					if (upload[i].length() > 5000) {
						addActionMessage("圖檔限110x40px/jpg/gif 5k以內");
						returnValue = "false";
						return "edit";
					}
					if (upload[i].length() > 0) {
						FileUtils.copyFile(upload[i], new File(sbMainPath.toString()));
					}
				}
				StringBuffer sbBrandImagePath = new StringBuffer();
				sbBrandImagePath.append(File.separator).append("static").append(File.separator).append("brand").append(
						File.separator).append(brand.getBrandId()).append(File.separator).append(brand.getBrandId()).append(".jpg");
				brand.setBrandImage(sbBrandImagePath.toString());
				productService.saveBrand(brand);
			}
			productService.saveBrandToFile(saveBrand.getBrandId(), brandStoryParam);
			if (null != saveBrand) {
				returnValue = "true";
			} else {
				addActionMessage("品牌名稱或同義詞已存在於資料庫中");
				returnValue = "false";
			}
		} catch (IOException e) {
			logger.info("BrandAction_save error :{}", e.toString());
		}
		return returnValue;
	}

	public String add() {
		brand = new Brand();
		brandId = null;
		setBrandStoryParam("");
		return "edit";
	}

	/**
	 * @return the productService
	 */
	public ProductService getProductService() {
		return productService;
	}

	/**
	 * @param productService the productService to set
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	/**
	 * @return the pager
	 */
	public SimplePager getPager() {
		return pager;
	}

	/**
	 * @param pager the pager to set
	 */
	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	/**
	 * @return the brands
	 */
	public List<Brand> getBrands() {
		return brands;
	}

	/**
	 * @param brands the brands to set
	 */
	public void setBrands(List<Brand> brands) {
		this.brands = brands;
	}

	/**
	 * @return the brandDelete
	 */
	public String[] getBrandDelete() {
		return brandDelete;
	}

	/**
	 * @param brandDelete the brandDelete to set
	 */
	public void setBrandDelete(String[] brandDelete) {
		this.brandDelete = brandDelete;
	}

	/**
	 * @return the brand
	 */
	public Brand getBrand() {
		return brand;
	}

	/**
	 * @param brand the brand to set
	 */
	public void setBrand(Brand brand) {
		this.brand = brand;
	}

	/**
	 * @return the brandId
	 */
	public String getBrandId() {
		return brandId;
	}

	/**
	 * @param brandId the brandId to set
	 */
	public void setBrandId(String brandId) {
		this.brandId = brandId;
	}

	/**
	 * @return the brandNameParam
	 */
	public String getBrandNameParam() {
		return brandNameParam;
	}

	/**
	 * @param brandNameParam the brandNameParam to set
	 */
	public void setBrandNameParam(String brandNameParam) {
		this.brandNameParam = brandNameParam;
	}

	public String getBriefNameParam() {
		return briefNameParam;
	}

	public void setBriefNameParam(String briefNameParam) {
		this.briefNameParam = briefNameParam;
	}

	public String getBrandStatusParam() {
		return brandStatusParam;
	}

	public void setBrandStatusParam(String brandStatusParam) {
		this.brandStatusParam = brandStatusParam;
	}

	public String getBrandStoryParam() {
		return brandStoryParam;
	}

	public void setBrandStoryParam(String brandStoryParam) {
		this.brandStoryParam = brandStoryParam;
	}

	public String getBrandEnameParam() {
		return brandEnameParam;
	}

	public void setBrandEnameParam(String brandEnameParam) {
		this.brandEnameParam = brandEnameParam;
	}

	public String getBrandSynonymParam() {
		return brandSynonymParam;
	}

	public void setBrandSynonymParam(String brandSynonymParam) {
		this.brandSynonymParam = brandSynonymParam;
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public Menu getStatusTypeMenu() {
		return statusTypeMenu;
	}

	public void setStatusTypeMenu(Menu statusTypeMenu) {
		this.statusTypeMenu = statusTypeMenu;
	}

}
